package cn.kgc.vue.controller;

import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.entity.Course;
import cn.kgc.vue.exceptions.BusinessException;
import cn.kgc.vue.response.ResponseResult;
import cn.kgc.vue.response.ResponseStatus;
import cn.kgc.vue.service.CourseService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import jakarta.annotation.Resource;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

/**
 * @author 课工场
 * @date 2024/10/6
 * @description
 */
@RestController
@RequestMapping("course")
public class CourseController {

    @Resource
    private CourseService courseService;

    // 课程列表
    @GetMapping("list")
    public ResponseResult courseList() {
        return courseService.courseList();
    }


    @PostMapping("page")
    public ResponseResult coursePage(@RequestBody QueryCondition<Course> queryCondition) {
        return courseService.coursePage(queryCondition);
    }


    @PostMapping("addOrUpdate")
    public ResponseResult addOrUpdateCourse(@RequestBody Course course) {

        try {
            courseService.saveOrUpdate(course);
            return ResponseResult.success();
        } catch (DuplicateKeyException e) {
            throw new BusinessException(ResponseStatus.ERROR.getCode(), "课程名字或编号重复");
        }

    }

    // 删除课程
    @DeleteMapping("delete/{id}")
    public ResponseResult editCourse(@PathVariable("id") Integer id) {

        LambdaUpdateWrapper<Course> lambda = new UpdateWrapper<Course>().lambda();
        lambda.set(Course::getIsDelete, 1)
                .eq(Course::getId, id);

        courseService.update(lambda);
        return ResponseResult.success();
    }


    // 课程状态编辑
    @PutMapping("editState/{id}/{state}")
    public ResponseResult editCourseState(@PathVariable("id") Integer id, @PathVariable("state") Integer state) {

        LambdaUpdateWrapper<Course> lambda = new UpdateWrapper<Course>().lambda();
        lambda.set(Course::getIsDelete, state)
                .eq(Course::getId, id);

        courseService.update(lambda);
        return ResponseResult.success();
    }

}
